package com.zykj.thread.concurrent.callablefuture;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author zhoulj(周利军) [1217102780@qq.com]
 * @Module ID:   <(模块)类编号，可以引用系统设计中的类编号>
 * @Comments: <对此类的描述，可以引用系统设计中的描述>
 * @JDK version used:      <JDK1.8> 17
 * @since 2019/1/15-11:17
 */
public class Demo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {


        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 3; i++) {
            Future<String> future = executorService.submit(new Callable<String>() {
                public String call() throws Exception {
                    Thread.sleep(1000);
                    return "测试用例...";
                }
            });
            System.out.println("等待结果...");
            String test = future.get();
            System.out.println(test);
        }

        //TODO 提交一组任务 并在其执行完成后  可以获取执行的结果
        System.out.println("使用一组线程池， 获取已完成的结果...");
        ExecutorService poolFixed = Executors.newFixedThreadPool(4);
        CompletionService completionService = new ExecutorCompletionService(poolFixed);
        for (int i = 0; i < 10; i++) {
            final int task = i ;
            completionService.submit(new Callable() {
                public Object call() throws Exception {
                    Thread.sleep(new Random().nextInt(2000));
                    return task;
                }
            });
        }
        for (int i = 0; i < 10; i++) {
            Future<Integer> future = completionService.take();
            System.out.println(future.get());
        }

    }
}
